<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/13
 * Time: 18:31
 */

namespace app\controller;
use rap\config\Config;
use Qiniu\Auth;
use rap\util\EncryptUtil;
use rap\web\Request;
use rap\web\Response;
use app\domain\user;
use Qiniu\Storage\UploadManager;
class CommonController
{
    public function getOcrData ($file, $category) {
        $host = "https://ocrsxz.market.alicloudapi.com";
        $path = "/discern/drivinglicense";
        $method = "POST";
        $appcode = "38e903dd5b414fa49385899c3ce8faf7";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        $bodys = json_encode([
            'ImageUrl' => $file,
            'Category'=>$category,
        ]);

        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

        //3.执行curl_exec($ch)
        $return_content = curl_exec($curl);

        //如果获取失败返回错误信息
        if($return_content === FALSE){
            $return_content = curl_errno($curl);
        }

        $return_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        //4.关闭curl
        curl_close($curl);

        return array($return_code, $return_content);
    }

    public function getCarNumberInfo($img){
        $host = "http://anpr.sinosecu.com.cn";
        $path = "/api/recogliu.do";
        $method = "POST";
        $appcode = "38e903dd5b414fa49385899c3ce8faf7";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "img=".$img;
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

        $data = curl_exec($curl);

        return $data;
    }

    public function getUserInfo ($token) {

        $config = Config::getFileConfig();
        $url = $config['app_info']['url'] . '?token=' . $token . '&secret=' . $config['app_info']['secret'];

        //初始化curl
        $ch = curl_init();
        //设置访问url
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //捕获内容，但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置请求超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

        $data = curl_exec($ch);
        //数据json解析
        $data = json_decode($data, true);
        //关闭curl
        curl_close($ch);
        //返回数据
        return $data;
    }


    public function getDriveLicenseInfo ($img, $cat) {

//        $img =  'http://image-lum.magcloud.cc/car.jpg';
        $url = 'http://ocrsxz.market.alicloudapi.com/discern/drivinglicense';
//        $cat = "driving";
        $data = [
            'ImageUrl' => $img,
            'Category'=>$cat,
        ];

        $data = json_encode($data);
        $appcode = "38e903dd5b414fa49385899c3ce8faf7";
        //1.初始化curl句柄
        $ch = curl_init();
        //2.设置curl
        //设置访问url
        curl_setopt($ch, CURLOPT_URL, $url);
        //捕获内容，但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //模拟发送POST请求
        curl_setopt($ch, CURLOPT_POST, 1);
        //发送POST请求时传递的参数
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //设置头信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)),
            'Authorization:APPCODE ' . $appcode
        );

        //3.执行curl_exec($ch)
        $return_content = curl_exec($ch);

        //如果获取失败返回错误信息
        if($return_content === FALSE){
            $return_content = curl_errno($ch);
        }

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        //4.关闭curl
        curl_close($ch);

        return array($return_code, $return_content);
    }

    public function success ($msg, array $array=[]) {

        return [
            'code' => 200,
            'msg' => $msg,
            'data' => $array,
        ];
    }

    public function false ($code, $msg, $data = []) {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }

    /**
     * 验证手机号是否正确
     * @param $phone
     */
    public function checkUserPhone ($phone) {
        $preg_phone='/^1[34578]\d{9}$/ims';
        //判断手机号格式是否正确
        if(preg_match($preg_phone,$phone)){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 验证身份证是否正确
     * @param $id_card
     */
    public function checkUserIdCard($id_card) {

        $chars = "/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/";
        if (preg_match($chars, $id_card)) {
            return true;
        } else {
            return false;
        }
    }


    public function getDateTime(){

        $date = date("Y-m-d H:i:s",time());

        return $date;
    }

    /**
     * 获取七牛云token
     */
    public function getQNToken() {

        $auth = new Auth(Config::getFileConfig()['qiniu']['AccessKey1'], Config::getFileConfig()['qiniu']['SecretKey1']);
        $data = $auth::uploadToken('chexun-imgs');

        return $data;
    }

    public function modifyGold($where) {

        $param = http_build_query($where);

        $goldUrl = Config::getFileConfig()['app_info']['goldUrl']. $param;
        //初始化curl
        $ch = curl_init();
        //设置访问url
        curl_setopt($ch, CURLOPT_URL, $goldUrl);
        //设置头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //捕获内容，但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置请求超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $data = curl_exec($ch);
        //数据json解析
        $data = json_decode($data, true);
        //关闭curl
        curl_close($ch);

        return  $data;

    }


    public function getHighPecPlace($param) {

        $url = "http://v.juhe.cn/wzpoints/query?";
        $url = $url . $param;

        //初始化curl
        $ch = curl_init();
        //设置访问url
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //捕获内容，但不输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置请求超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

        $data = curl_exec($ch);
        //数据json解析
        $data = json_decode($data, true);
        //关闭curl
        curl_close($ch);
        //返回数据
        return $data;
    }

    public function uploadFile (Request $request) {


//        return $_FILES['pic']['tmp_name'];


        $auth = new Auth(Config::getFileConfig()['qiniu']['AccessKey1'], Config::getFileConfig()['qiniu']['SecretKey1']);  //实例化
        $bucket='chexun-imgs';//存储空间
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        $filePath = $_FILES['pic']['tmp_name'];//'./php-logo.png';  //接收图片信息
        //名称图片
        $key = time().'.png';

        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return self::false(404, '上传失败', []);
        }

        if ( $ret['key']) {
            $data = [
                'pic_url' => Config::getFileConfig()['qiniu']['domain'] . '/' . $ret['key']
            ];
            return self::success('上传成功', $data);
        } else {
            return self::false(404, '上传失败', []);
        }
    }

    public function getOrderNumber($length){

        //订购日期

        $order_date = date('Y-m-d');

        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）

        $order_id_main = date('YmdHis') . rand(10000000,99999999);

        //订单号码主体长度

        $order_id_len = strlen($order_id_main);

        $order_id_sum = 0;

        for($i=0; $i<$order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $random = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);

        return $random;
    }

    public function getRandom($length){
        $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }

        return $randstr;
    }

    public function getPersonalInfo ($res, $token){
        $data = $res['data'];
        $data['token'] = $token;
        $data['nickname'] = $data['name'];
        unset($data['name']);
        unset($data['regist_time']);
        $data['update_time'] = date("Y-m-d H:i:s", time());

        $where = [
            'user_id' => $data['user_id'],
            'is_del' => 0
        ];
        $res = user::getUserAuthInfo($where, "*");
        $gold = user::getUserGoldCount($data['user_id']);
        if ($res) {
            user::updateUserAuth($where, $data);
        } else {
            user::insertUserAuth($data);

        }
        //获取用户壁虎币数量
        $data['gold'] = $gold;
        $_SESSION[$token] = $data;
        return $data;
    }
    
    public function getImageBase64 (Request $request) {
        //允许跨域访问
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
        header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
        header('Access-Control-Max-Age: 1728000');

        if ($request -> method() == "POST") {
            $img = $request->param('img', '');

            $imageInfo = getimagesize($img);
//            $base64 = "" . chunk_split(base64_encode(file_get_contents($img)));
            $base64_image = 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
            return self::success('获取数据成功', [
                'img' => $base64_image
            ]);
        }

    }
}